import Utils from "../game/GameUtils";
import Logger from "../utils/Logger";
import { Room, RoomState } from "./Room";
import { User } from "./User";

/**
 * 游戏总控
 */
class HallMgr {

    users: Map<string,User> = new Map<string,User>();       //全部玩家
    rooms: Set<Room> = new Set<Room>();                     //匹配房合集
    cipherRooms: Set<Room> = new Set<Room>();               //密码房合集
    room_number:number = 0;                                 //创建房间的个数，同时也是room的id值

    /** 匹配 */
    match(user: User) {
        for(let room of this.rooms){
            if(room.checkAddPlayer()){
                room.addPlayer(user)
                return;
            }
        }
        let room:Room = new Room(++this.room_number);
        room.addPlayer(user);
        this.rooms.add(room);
    }

    /** 创建或加入房间 */
    createOrjoinRoom(user:User,cipher:string) {
        for(let room of this.cipherRooms) {
            if(room.checkCipherRoomAddPlayer(cipher)) {
                room.addPlayer(user);
                return;
            }
        }
        let room:Room = new Room(++this.room_number,cipher);
        room.addPlayer(user);
        this.cipherRooms.add(room);
    }

    /** 观战 */
    watchingRoom(user: User) {
        for(let room of this.cipherRooms) {
            if(room.state == RoomState.GAMEING) {
                room.addPlayer(user);
                return;
            }
        }
        let json = JSON.stringify(Utils.getObj("watchFail",{"message":"没有对局，无法观战"},false));
        user.connection.sendText(json);
    }

    /** 聊天 */
    chat(obj:any) {
        var json = JSON.stringify(Utils.getObj("chat",obj.data,false));
        Logger.log("send:"+json);
        for(let value of this.users.values()) {
            value.connection.sendText(json);
        }
    }

    /** 在线人数，这里只返回在大厅的人数，在游戏中的不管 */
    updateOnline() { 
        let num = 0
        for(let user of this.users.values()) {
            if (user.room == null || user.room.state == RoomState.MATCHING) {
                num++ 
            }
        }
        var json = JSON.stringify(Utils.getObj("updateOnline",{"number":num},false));
        Logger.log("send: "+json);
        for(let value of this.users.values()) {
            value.connection.sendText(json);
        }
    }
}

export default new HallMgr();